<template>
    <div>
      <cfg-table
        ref="table"
        :columns="columns"
        :data="data"
        :loading="loading"
        :config="config"
        :pageSizeOpts="pageSizeOpts"
        :pageNavigation="pageNavigation"
        :queryFormItem="queryFormItem"
        :collapseFormItem="collapseFormItem"
        :additionalAction="additionalAction"
        @loadPage="loadPage"
        @handleCreate="handleCreate"
        @handleDetail="handleDetail"
        @handleEdit="handleEdit"
        @handleDelete="handleDelete"
        @handleDeleteMultiple="handleDeleteMultiple"
        @handleSearch="handleSearch"
        @handleReset="handleReset"
      ></cfg-table>
      <warn-new-add-modal
        v-bind="addNewPanel"
        ref="addModal"
        :modelType="modelType"
        :columns="formColumns"
        :rules="rules"
        :energyList="energyList"
        @submit="handleNewAddSubmit"
      ></warn-new-add-modal>
      <warn-edit-modal
        v-bind="editPanel"
        :modelType="modelType"
        :columns="formColumns"
        :rules="rules"
        :energyList="energyList"
        @submit="handleEditSubmit"
      ></warn-edit-modal>
      <read-modal
        v-bind="readPanel"
        :modelType="modelType"
        :columns="columns"
        :rules="rules"
      ></read-modal>
      <!-- 绑定预警负责人 -->
        <!-- <bind-account
            :accountPanel="accountPanel"
            :isSingleCheck="isSingleCheck"
            :selectionData="selectionData"
            @submit="handleAccountSelectSubmit"
        ></bind-account> -->
    </div>
</template>

  <script>
    import warnNewAddModal from './components/warnNewAddModal.vue';
    import warnEditModal from './components/warnEditModal.vue';
    import readModal from '@/pages/components/readModal.vue';
    import { typeClassName } from '@/pages/config/classNameMap';
    import mixin from '@/pages/components/mixins/mixin'
    import bindAccount from '@/pages/components/bindAccount';
    import columnsMixin from './config'
    export default {
        components: { warnNewAddModal,warnEditModal,readModal, bindAccount },
        name: 'energyWarnSetting',
        mixins: [mixin, columnsMixin],
        data () {
            return {
                classObject: null, // 单个实例
                collectionObject: null, // 所有实例
                className: typeClassName['energyWarnSetting'].className,
                type: typeClassName['energyWarnSetting'].type,
                modelType: typeClassName['energyWarnSetting'].modelType,
                energyClassObject: null, // 能源实例
                selectionData: [], // 绑定预警负责人
                isSingleCheck: false,
                addNewPanel: {
                    width: 1024,
                    zIndex: 100,
                    titleStyle: {},
                    drawer: {
                        show: false
                    },
                    cols: 2
                },
                editPanel: {
                    width: 1024,
                    zIndex: 100,
                    titleStyle: {},
                    drawer: {
                        show: false
                    },
                    cols: 2,
                    data: {}
                },
                readPanel: {
                    width: 1024,
                    zIndex: 100,
                    titleStyle: {},
                    drawer: {
                        show: false
                    },
                    cols: 2,
                    data: {}
                },
                accountPanel: {
                    width: 1024,
                    zIndex: 100,
                    titleStyle: {},
                    drawer: {
                        show: false
                    },
                    cols: 2,
                    data: {}
                },
                rules: {
                    sf_code: [
                        { required: true, message: '不能为空', trigger: 'blur' }
                    ],
                    sf_name: [
                        { required: true, message: '不能为空', trigger: 'blur' }
                    ],
                    sf_energyCode: [
                        { required: true, message: '不能为空', trigger: 'blur' }
                    ],
                    sf_energyName: [
                        { required: true, message: '不能为空', trigger: 'blur' }
                    ],
                    sf_energyType: [
                        { required: true, message: '不能为空', trigger: 'blur' }
                    ],
                    sf_pointName: [
                        { required: true, message: '不能为空', trigger: 'blur' }
                    ],
                    sf_scale: [
                        { required: true,message: '不能为空', trigger: 'blur' }
                    ],
                    df_upperLimit: [
                        { required: true,type: 'number', message: '不能为空', trigger: 'blur' }
                    ],
                    df_upLimit: [
                        { required: true,type: 'number', message: '不能为空', trigger: 'blur' }
                    ],
                    df_lowLimit: [
                        { required: true,type: 'number', message: '不能为空', trigger: 'blur' }
                    ],
                    df_lowerLimit: [
                        { required: true,type: 'number', message: '不能为空', trigger: 'blur' }
                    ],
                },
                loading: false,
                config: {
                    search: true,
                    addButton: true,
                    batchDeleteButton: true,
                    tableSizeIcon: true,
                    fullscreenIcon: true,
                    refreshIcon: false,
                    columnSettingIcon: true,
                    action: true,
                    additionalAction: false
                },
                pageSizeOpts: [10, 30, 50, 100],
                pageNavigation: { total: 0, pageSize: 10, pageNumber: 1 },
                colorOptions:[
                  {label:'红色',value:'红色'},
                  {label:'橙色',value:'橙色'},
                  {label:'蓝色',value:'蓝色'},
                ],
                energyCodeOptions:[],
                energyList:[],
                scaleOptions:[
                  {label:'时',value:'时'},
                  {label:'分',value:'分'},
                ],
            };
        },
        computed: {
            additionalAction () {
                let additionalAction = {
                    key: 'additionalAction',
                    title: {
                        'zh-CN': '附加操作',
                        'en-US': 'additional action'
                    }[this.G_Locale],
                    slot: 'additionalAction',
                    width: 200,
                    fixed: 'right',
                    align: 'center',
                    show: true,
                    buttons: [
                        // {
                        //     title: {
                        //         'zh-CN': '设置预警',
                        //         'en-US': 'setWarning'
                        //     }[this.G_Locale],
                        //     event: (row, index) => this.handleEdit(row, index)
                        // },
                        // {
                        //     title: {
                        //         'zh-CN': '绑定负责人',
                        //         'en-US': 'setWarning'
                        //     }[this.G_Locale],
                        //     event: (row, index) => this.bindNotifier(row, index)
                        // }
                    ]
                }
                this.G_IsMobile && (additionalAction.width = 90)
                return additionalAction;
            },
            data () {
                if (!!this.collectionObject) {
                    return this.collectionObject.records.map(d => {
                        return {
                            ...d,
                            ...d.values
                        }
                    })
                } else {
                    return [];
                }
            }
        },
        beforeMount () {
            this.collectionObject = this.$modelObject.create(`${this.modelType}Collection`);
            this.classObject = this.$modelObject.create(this.modelType);
            this.energyClassObject = this.$modelObject.create(`${typeClassName['energyInfo'].modelType}`);
            this.loadPage(this.pageNavigation, null);
            // 能源名称
            let energyInfoFilter = {
                className: typeClassName['energyInfo'].className,
                type: typeClassName['energyInfo'].type
            }
            this.getEnergyCodeOptions(energyInfoFilter)
        },
        mounted () {},
        methods: {
            // 设置预警
            async handleEdit (row, index) {
                this.loading = true;
                if (await this.getRecord({ type: row.type, className: row.className, id: row.id })) {
                    this.$set(this.editPanel, 'data', this.classObject.record);
                    this.$set(this.editPanel.drawer, 'show', true);
                    this.loading = false;
                } else {
                    this.loading = false;
                }
            },
            // 绑定预警负责人
            async bindNotifier (row) {
                if (await this.getRecord({ type: row.type, className: row.className, id: row.id })) {
                    this.selectionData = this.classObject.record.values.notifier || []
                    this.$set(this.accountPanel.drawer, 'show', true)
                    this.loading = false;
                } else {
                    this.loading = false;
                }
            },
            getPersonName (person) {
               if (!Array.isArray(person)) {
                   return person
               } else {
                   return person.map(d => d.personName).join(',')
               }
            },
            // 预警负责人确定
            handleAccountSelectSubmit (selection) {
                let notifier = selection
                this.$set(this.classObject.record.values, 'notifier', notifier)
                this.selectionData = selection
                let pointer = { className: this.className, type: this.type, id: this.classObject.record.id }
                let newData = selection.map(d => {
                    return {
                        values: {},
                        name: 'account-' + String(d.personId),
                        id: d.personId,
                        model: '',
                        pointer: {}
                    }
                })
                let originalData = [];
                if (!!this.classObject.hier && this.classObject.hier.length > 0) {
                    this.classObject.hier[0].basic.forEach(item => {
                        if (!item.name.startsWith('account-')) {
                            originalData.push({ ...item })
                        }
                    })
                }
                newData = [...newData, ...originalData]
                this.run(pointer, newData, this.accountPanel)
            },
            run (pointer, newData, selectPanel) {
                this.collectionObject.run([
                    {
                        action: 'RUN_ALL_ADD_REGISTER',
                        model: this.modelType,
                        pointer,
                        hier: [{ basic: newData }]
                    },
                    {
                        action: 'UPDATE',
                        model: this.modelType,
                        data: [this.classObject.record]
                    }
                ]).then(flag => {
                    if (flag) {
                        let index = this.collectionObject.records.findIndex(
                            (item) => item.id === this.classObject.record.id
                        );
                        if (index !== -1) {
                            this.collectionObject.records.splice(
                                index,
                                1,
                                this.classObject.record
                            );
                        }
                        this.loading = false;
                        this.$set(selectPanel.drawer, 'show', false);
                    } else {
                        this.loading = false;
                    }
                })
            },
            getEnergyCodeOptions(condition){
               this.$api.TemplateInstance.query(condition).then(res=>{
                  if(!res){
                     this.energyCodeOptions = [];
                     this.energyList = [];
                     return;
                  }
                  this.energyList = res.map(d=>d.values)
                  this.energyCodeOptions = res.map(d=>({label:d.values.sf_energyName,value:d.values.sf_energyCode}))
               })
            },
        }
    };
  </script>
  <style scoped lang="scss"></style>
